export async function openDB(): Promise<IDBDatabase> {
  return new Promise((resolve, reject) => {
    const request = indexedDB.open('FileHandlesDB', 2);
    request.onupgradeneeded = (event) => {
      // @ts-ignore
      const db = event.target.result;
      if (!db.objectStoreNames.contains('files')) {
        db.createObjectStore('files');
      }
    };
    request.onsuccess = () => resolve(request.result);
    request.onerror = () => reject(request.error);
  });
}

// 获取存储的文件句柄
export async function getStoredFileHandle(
  db: IDBDatabase,
  key: string,
): Promise<FileSystemDirectoryHandle | undefined> {
  return new Promise((resolve, reject) => {
    const tx = db.transaction('files', 'readonly');
    const request = tx.objectStore('files').get(key);
    request.onsuccess = () => resolve(request.result);
    request.onerror = () => reject(request.error);
  });
}

// 存储文件句柄
export const storeFileHandle = async (
  handle: FileSystemDirectoryHandle,
  key: string,
  db: IDBDatabase,
) => {
  const tx = db.transaction('files', 'readwrite');
  tx.objectStore('files').put(handle, key);
};
